#!/usr/bin/env python
# -*- coding: utf8 -*-

''' 
# =======
# User: luwei
# Date: 11-4-22
# Time: 下午2:42
# email = luw2007@gmail.com
# =======
# check_server2 import htmllib 和 check_server import socket .两者不一样。
'''

# Imports
# =======
import sys
import httplib


def check_web_server(address, port, resource):
    #Build up HTTP request string
    if not resource.startswith('/'):
        resource = '/' + resource
    try:
        conn = httplib.HTTPConnection(address, port)
        print "HTTP connection created successfully"
        #make request
        req = conn.request('GET', resource)
        print "HTTP request for ", resource, "successful."
        #get response
        respones = conn.getresponse()
        print "response status: ", respones.status
    except sock.error, e:
        print "HTTP connect failed: " , e
        return False
    finally:
        conn.close()
        print "Closing the connection"
    if respones.status in [200, 301]:
        print "Success -status was ", respones.status
        return True
    else:
        print "Status was ", respones.status
        return False

def check_web_server_input():
    from optparse import OptionParser
    parser = OptionParser()
    parser.add_option('-a', "--address", dest="address", default="www.xinnet.com", help="ADDRESS for the server", metavar="ADDRESS")
    parser.add_option('-p', "--port", dest="port", type="int", default="80", help="PORT for the server", metavar="PORT")
    parser.add_option('-r', "--resource", dest="resource", default="index.html", help="RESOURCE to check", metavar="RESOURCE")

    (options, args) = parser.parse_args()
    print "options: " , options , "args: " , args
    check = check_web_server(options.address, options.port, options.resource)
    print "check_web_server resturn " , check
    sys.exit(not check)


def main():
    '''test main'''
    print "done"

if __name__ == '__main__':
    check_web_server_input()
    main()



#def check_web_server_by_host(address, port, host, resource):
    #Build up HTTP request string
    if not resource.startswith('/'):
        resource = '/' + resource
    #request_string = "GET" + resource + "HTTP/1.1\r\nHOST: " + address + "\r\n\r\n"
    request_string = "GET %s HTTP/1.1\r\nHOST: %s \r\n\r\n" % (resource, host)
    print "HTTP request"
    print "|||", request_string, "|||"

    # creat a TCP socket
    s = socket.socket()
    print "Attempting to connect to " , address , "on the port" , port
    try:
        s.connect((address, port))
        print "Connect to " , address , "on the port" , port
        s.send(request_string)
        # noly get the first 100 bytes
        rsp = s.recv(100)
        print "Recived 100 bytes of HTTP response"
        print "|||", rsp, "|||"
    except socket.error, e:
        print "Connect to " , address , "on the port" , port , "failed: " , e
        return False
    finally:
        print "Closing the connection"
        s.close()
    lines = rsp.splitlines()
    print "First line of HTTP response: %s " % lines[0]
    try:
        version, status, message = re.split(r'\s+', lines[0], 2)
        print "Version: ", version, "Status: ", status, "Message: ", message
    except ValueError:
        print "Failed to split status line"
        return False
    if status in ['200', '301']:
        print "Success -status was ", status
        return
    else:
        print "Status was ", status
        return False

#def check_web_server_by_host_input():
    from optparse import OptionParser
    parser = OptionParser()
    parser.add_option('-a', "--address", dest="address", default="61.135.169.125", help="ADDRESS for the server", metavar="ADDRESS")
    parser.add_option('-p', "--port", dest="port", type="int", default="80", help="PORT for the server", metavar="PORT")
    parser.add_option('-H', "--host", dest="host", default="www.baidu.com", help="hostname for the server", metavar="HOST")
    parser.add_option('-r', "--resource", dest="resource", default="index.html", help="RESOURCE to check", metavar="RESOURCE")

    (options, args) = parser.parse_args()
    print "options: " , options , "args: " , args
    check = check_web_server_by_host(options.address, options.port, options.host, options.resource)
    print "check_web_server resturn " , check
    sys.exit(not check)
